#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

class ThreadPool {
public:
    explicit ThreadPool(size_t n = 1) {
        for (size_t i = 0; i < n; ++i) {
            threads_.emplace_back(&ThreadPool::worker, this, static_cast<int>(i));
        }
    }

    ~ThreadPool() {
        std::cout << "[Main] 开始析构线程池\n";
        isRunning_ = false;

        std::unique_lock<std::mutex> lock(mtx_);
        notEmpty_.notify_all();

        exitCond_.wait(lock, [this]() { return activeThreads_ == 0; });
        std::cout << "[Main] 析构结束\n";

        lock.unlock();
        for (auto &t : threads_) {
            if (t.joinable()) {
                t.join();
            }
        }
    }

private:
    void worker(int id) {
        {
            std::lock_guard<std::mutex> guard(mtx_);
            ++activeThreads_;
            std::cout << "[Worker " << id << "] 启动\n";
        }

        while (true) {
            std::unique_lock<std::mutex> lock(mtx_);
            notEmpty_.wait(lock, [this]() {
                return !tasks_.empty() || !isRunning_;
            });

            if (!isRunning_ && tasks_.empty()) {
                std::cout << "[Worker " << id << "] 感知关闭，退出\n";
                --activeThreads_;
                exitCond_.notify_all();
                return;
            }

            // 在这儿正常消费任务（示例中没有真正的任务）
        }
    }

    std::vector<std::thread> threads_;
    std::mutex mtx_;
    std::condition_variable notEmpty_;
    std::condition_variable exitCond_;
    bool isRunning_{true};
    int activeThreads_{0};
    std::vector<int> tasks_;
};

int main() {
    ThreadPool pool(1);
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "[Main] main 结束，触发析构\n";
    return 0;
}